<?php

namespace addons\hlapp\controller;

use addons\hlapp\dto\Result;
use addons\hlapp\model\CacheEnum;
use addons\hlapp\model\HlappEvaluateSendLogs;
use addons\hlapp\model\HlappMember;
use addons\hlapp\model\HlappPart;
use addons\hlapp\model\HlappProject;
use addons\hlapp\model\HlappProjectEvaluate;
use addons\hlapp\model\HlappProjectType;
use addons\hlapp\model\HlappTypeStage;
use addons\hlapp\service\CacheService;
use function PHPSTORM_META\type;
use think\Db;
use think\Exception;

class Project extends Common
{
    public $adminLogin = true;//注意：因为这是后台业务菜单所以需要管理员登录操作的
    public $pageSize = 10;

//-------------
//---- 页面
//-------------

    public function test()
    {
        $data = HlappTypeStage::getTypeStage();
        echo json_encode($data);
    }

    /**
     * 项目详情pagelist
     */
    public function projectInfo()
    {
//        $e = new HlappProjectEvaluate();
//        $evaluates = $e->where('projectId', $_GET['projectId'])->select();
        $project = HlappProject::getProject($_GET['projectId']);
//        $this->assign('evaluates', $evaluates);
        $this->assign('project', $project);
        $this->fetch();
    }

    /**
     * 项目推送页面
     */
    public function pagepush()
    {
        $name = $this->request->param("name");
        $position = $this->request->param("position");
        $type = $this->request->param("type");
        $evaStatus = $this->request->param("evaStatus");
        //未选择
        if ($evaStatus == ""){
            $list = Db::name('hlapp_project p')
                ->field('p.*')
                ->where('name', 'like', '%' . $name . '%')
                ->where('position', 'like', '%' . $position . '%')
                ->where('type', 'like', '%' . $type . '%')
                ->where('status', '>', 0)
                ->where('amamager_id', '>', 0)
                ->where('delete_time is null')
                ->order('id', 'desc')
                ->paginate($this->pageSize, false, ['query' => request()->param()]);
        }else{
            $list = Db::name('hlapp_project p')
                ->field('p.*')
                ->where('name', 'like', '%' . $name . '%')
                ->where('position', 'like', '%' . $position . '%')
                ->where('type', 'like', '%' . $type . '%')
                ->where('status', '>', 0)
                ->where('amamager_id', '>', 0)
                ->where('delete_time is null')
                ->where('isPush',1)
                ->where('isEvaluated',$evaStatus)
                ->order('id', 'desc')
                ->paginate($this->pageSize, false, ['query' => request()->param()]);
        }


        $page = request()->param('page');
        $types = HlappProjectType::getProjectType();
        $page || ($page = 1);
        $this->assign('list', $list);
        $this->assign('page', $page);
        $this->assign('name', $name);
        $this->assign('type', $type);
        $this->assign('position', $position);
        $this->assign('evaStatus', $evaStatus);
        $this->assign("typeList", $types);
        return $this->fetch();
    }

    /**
     * 項目人员登记信息关联
     */
    public function projectAndMemberInfo()
    {
        $regist = $this->request->param("regist");
        if ($regist){
            $list = Db::name('hlapp_project p')
                ->field('p.id p_id,p.name p_name,p.type p_type,p.stage p_stage,p.status p_status,m.name m_name,m.openId m_openId')
                ->leftJoin('hl_hlapp_member m','p.amamager_id = m.id')
                ->where('p.delete_time is null')
                ->where('m.delete_time is null')
                ->where('m.openId is not null')
                ->order('p.id', 'desc')
                ->paginate($this->pageSize, false, ['query' => request()->param()]);
        }else if ($regist == '0'){
            $list = Db::name('hlapp_project p')
                ->field('p.id p_id,p.name p_name,p.type p_type,p.stage p_stage,p.status p_status,m.name m_name,m.openId m_openId')
                ->leftJoin('hl_hlapp_member m','p.amamager_id = m.id')
                ->where('p.delete_time is null')
                ->where('m.delete_time is null')
                ->where('m.openId is null')
                ->order('p.id', 'desc')
                ->paginate($this->pageSize, false, ['query' => request()->param()]);
        }else{
            $list = Db::name('hlapp_project p')
                ->field('p.id p_id,p.name p_name,p.type p_type,p.stage p_stage,p.status p_status,m.name m_name,m.openId m_openId')
                ->leftJoin('hl_hlapp_member m','p.amamager_id = m.id')
                ->where('p.delete_time is null')
                ->where('m.delete_time is null')
                ->order('p.id', 'desc')
                ->paginate($this->pageSize, false, ['query' => request()->param()]);
        }

        $page = request()->param('page');
        $this->assign('list', $list);
        $this->assign('page', $page);
        $this->assign("regist", $regist);
        return $this->fetch();
    }


    /**
     * 项目评价信息推送
     */
    public function pushEvaluates()
    {
        $ids = $_POST['ids'];
        $errorName = "";
        $projects = (new HlappProject())->select($ids);
        $r = Result::getResultOk();
        $message = "";
        foreach ($projects as $project) {
            if ($message != "") {
                $message = $message . "、";
            }
            try {
                \Log::INFO("项目id：" . $project["id"] . " 执行推送方法");
                if ($project['amamager_id']) {
                    $week = $this->getWeekOfYear(time());
                    //取消开始周数大于0的判断
//                if($week > 0){
                    $e = new HlappProjectEvaluate();
                    $evaluate['projectId'] = $project['id'];
                    $evaluate['stage'] = $project->getData('stage');
                    $evaluate['week'] = $week;
                    $evaluate0 = $e->where($evaluate)->find();
                    if ($evaluate0) {
                        \Log::INFO("评价已存在");
                        $eid = $evaluate0['id'];
                    } else {
                        $eid = $e->saveOrUpdata($evaluate);
                    }
                    $member = HlappMember::get($project['amamager_id']);
                    if ($eid) {
                        \Log::INFO("发送评价消息");
                        $res = (new Open())->sendEvaluateToMember($project['id'], $member['openId'], $week, $eid);
                        if ($res->code) {
                            \Log::INFO($project->id . "发送模板消息成功！");
                        } else {
                            $r->setCode(0);
                            $message = $message . $project->id;
                            \Log::ERROR($project->id . "发送模板消息失败！ ");
                            \Log::ERROR(json_encode($res, JSON_UNESCAPED_UNICODE));
                        }
                    } else {
                        $r->setCode(0);
                        $message = $message . $project->id;
                    }
//                }
                } else {
                    \Log::ERROR("没有录入甲方项目经理！");
                    $message = $message . $project->id;
                }
            } catch (\Exception $e) {
                $r->setCode(0);
                \Log::ERROR("异常抛出错误：" . $e->getMessage());
                \Log::ERROR("异常文件：" . $e->getFile());
                \Log::ERROR("异常行数：" . $e->getLine());
                $message = $message . $project['id'];
            }
        }
        $r->setMessage("项目编号 " . rtrim($message, '、') . " 推送失败！");
        return $r->toJson();
    }

    /**
     * 分页
     */
    public function pagelist()
    {
//        $m = new HlappProject();
        $name = $this->request->param("name");
        $position = $this->request->param("position");
        $m = new HlappProject();
        $list = $m->where('name', 'like', '%' . $name . '%')
            ->where('position', 'like', '%' . $position . '%')->order('id', 'desc')->paginate($this->pageSize, false, ['query' => request()->param()]);
        $page = request()->param('page');
        $page || ($page = 1);
        $this->assign('list', $list);
        $this->assign('page', $page);
        $this->assign('name', $name);
        $this->assign('position', $position);
        return $this->fetch();
    }

    /**
     * 添加页面
     */
    public function addpage()
    {
        $parts = (new HlappPart())->with('members')->select();
        $this->assign('parts', $parts);
        return $this->fetch();
    }

    /**
     * 添加方法
     */
    public function add()
    {
        return Result::getOk((new HlappProject())->saveOrUpdata($_POST));
    }

    /**
     * 删除方法
     */
    public function delete()
    {
        $r = Result::getError();
        try {
            $id = $_POST['id'];
            $p = HlappProject::get($id);
            $p->together('rolesMember')->delete();
            $r = Result::getOk();
        } catch (Exception $e) {

        }
        return $r;

    }

    /**
     * 更新页面
     */
    public function updatepage()
    {
        $id = $_GET['id'];
        $project = (new HlappProject())->getProject($id);
        $this->assign('project', $project);
        $parts = (new HlappPart())->with('members')->where('id','in',HlappPart::$NOCENTERTYPE)->select();
        $this->assign('parts', $parts);
        return $this->fetch();
    }

    /**
     * 获取项目下一阶段
     * @throws \think\exception\DbException
     */
    public function nextStage()
    {
        $pid = $_POST['pid'];
        $project = HlappProject::getProject($pid);
        if ($project['stage']) {
            $stage = HlappTypeStage::getNextStage($project->getData('type'), $project->getData('stage'));
        } else {
            $stage = HlappTypeStage::getNextStage($project->getData('type'));
        }
        return Result::getOk($stage);
    }

    /**
     * 开始项目
     */
    public function startProjectB($p_id)
    {
        $result = Result::getResultOk();
        $p = new HlappProject();
        $project = $p->where('id', $p_id)->find();
        if ($project['status'] == 0) {
            $project['status'] = 1;
            if (!$project['stage']) {
                $stage = HlappTypeStage::getNextStage($project->getData('type'));
            }
            $project['stage'] = $stage['id'];
            $project->save();
        } else {
            $result->setMessage("项目已经开始");
            $result->setCode(0);
        }
        return $result;
    }

    /**
     * 页面
     * 开始项目
     */
    public function startProject()
    {
        try {
            (new HlappProject())->saveOrUpdata($_POST);
            $r = Result::getOk();
        } catch (\Exception $e) {
            $r = Result::getError("更新失败！");
        }
        return $r;
    }

    /**
     * 更新方法
     */
    public function update()
    {
        try {
            (new HlappProject())->saveOrUpdata($_POST);
            $r = Result::getOk();
        } catch (\Exception $e) {
            $r = Result::getError("更新失败！");
        }
        return $r;
    }

    //导入页面
    public function importpage()
    {
        $this->fetch();
    }


    //导入项目信息
    public function import()
    {
        $message = "导入失败！";
        // 获取表单上传文件
        $file = request()->file('file');
        if (empty($file)) {
            $this->error('请选择上传文件');
        }
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        \Log::INFO("上传信息 ：");
        \Log::INFO($info);
        if ($info) {
            $fileName = $info->getFilename();
            $fix = substr(strrchr($fileName, '.'), 1);
            \Log::INFO("上传文件后缀名：" . $fix);
            \Log::INFO("上传文件名：" . $info->getSaveName());
            if ($fix == 'xlsx') {
                $filepath = $info->getSaveName();
                $filepath = ROOT_PATH . 'public' . DS . 'uploads' . DS . $filepath;
                \Log::INFO("上传文件目录：" . $filepath);
                $message = $this->importExcel($filepath);
            } else {
                $message = "请导入模板格式文件";
            }

            $this->success($message, null, '', 60);
        } else {
            // 上传失败获取错误信息
            $this->error($file->getError(), null, '', 60);
        }
    }

    public function importExcel($file)
    {
        $result = "导入成功！";
        $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        $obj_PHPExcel = $objReader->load($file, $encode = 'utf-8');//加载文件内容,编码utf-8  
        $excel_array = $obj_PHPExcel->getsheet(0)->toArray();//转换为数组格式  
        array_shift($excel_array);//删除第一个数组(标题);
        $i = 0;
        \Log::INFO("输出内容：--");
        \Log::INFO(json_encode($excel_array, JSON_UNESCAPED_UNICODE));

        //检查excel格式
        $result = $this->checkData($excel_array);
        if ($result) {
            //校验不通过
            \Log::ERROR($result);
        } else {
            //项目信息插入数据库
            $result = $this->addExcel($excel_array);
        }
        return $result;
    }

    //校验excel数据
    public function checkData($excel_array)
    {
        if (count($excel_array) > 150) {
            return "文件大小超过150！,不允许导入";
        }
        $result = "";
        $p_names = array();
        foreach ($excel_array as $row) {
            $p_name = trim($row[0]);
            $p_position = trim($row[1]);
            $p_customer = trim($row[2]);
            $p_type = trim($row[3]);
            $p_amamager_name = trim($row[4]);
            $p_amamager_phone = trim($row[5]);
            $p_manager_name = trim($row[6]);
            $p_manager_phone = trim($row[7]);
            $p_engineer_name = trim($row[8]);
            $p_engineer_phone = trim($row[9]);
            //空校验
            if (!$p_name) {
                $result = "项目名称不能为空";
                break;
            }
            if (!$p_position) {
                $result = "项目位置不能为空";
                break;
            }
            if (!is_numeric($p_type)) {
                $result = $p_name . "项目类型错误！";
                break;
            }

            if (!$p_amamager_name && !$p_amamager_phone) {
                $result = $p_name . " 项目 甲方项目经理 信息不能为空！";
                break;
            }
            if (!isMobileNumber($p_amamager_phone)) {
                $result = $p_name . " 项目 甲方项目经理 手机号格式错误！";
                break;
            }
            //区域总负责人
            if ($p_manager_name || $p_manager_phone) {
                $role = "区域总负责人";
                if (!$p_manager_name && !$p_manager_phone) {
                    $result = $p_name . "项目中 " . $role . " 信息不能为空！";
                    break;
                }
                if (!isMobileNumber($p_manager_phone)) {
                    $result = $p_name . "项目中 " . $role . " 手机号格式错误！";
                    break;
                }
            }
            //区域工程负责人
            if ($p_engineer_name || $p_engineer_phone) {
                $role = "区域工程负责人";
                if (!$p_manager_name && !$p_manager_phone) {
                    $result = $p_name . "项目中 " . $role . " 信息不能为空！";
                    break;
                }
                if (!isMobileNumber($p_manager_phone)) {
                    $result = $p_name . "项目中 " . $role . " 手机号格式错误！";
                    break;
                }
            }
            array_push($p_names, $p_name);
        }
        $p = new HlappProject();
        $projects = $p->where("name", 'in', $p_names)->select();
        if (count($projects) > 0) {
            $project_name = "项目名称";
            foreach ($projects as $project) {
                $project_name = $project_name . $project['name'] . "、";
            }
            $result = $result . "  " . $project_name . " 已存在! 导入表格失败";
        }
        return $result;
    }

    //插入excel
    private function addExcel($excel_array)
    {
        $time = time();
        $result = "导入成功";
        \Log::INFO("excel 插入时间 :" . $time . "  data:" . date("Y-m-d H:i:s", $time));
        foreach ($excel_array as $row) {
            Db::startTrans();
            try {
                $p_name = trim($row[0]);
                $p_position = trim($row[1]);
                $p_customer = trim($row[2]);
                $p_type = trim($row[3]);
                $p_amamager_name = trim($row[4]);
                $p_amamager_phone = trim($row[5]);
                $p_manager_name = trim($row[6]);
                $p_manager_phone = trim($row[7]);
                $p_engineer_name = trim($row[8]);
                $p_engineer_phone = trim($row[9]);

                $amamager_id = $this->insertNotExit($p_amamager_name, $p_amamager_phone, $time, 4);
                $manager_id = 0;
                $engineer_id = 0;
                if ($p_manager_name) {
                    $manager_id = $this->insertNotExit($p_manager_name, $p_manager_phone, $time, 6);
                }
                if ($p_engineer_name) {
                    $engineer_id = $this->insertNotExit($p_engineer_name, $p_engineer_phone, $time, 7);
                }
                $project["name"] = $p_name;
                $project["position"] = $p_position;
                $project["customer"] = $p_customer;
                $project["type"] = $p_type;
                $project["amamager_id"] = $amamager_id;
                $project["amamager_name"] = $p_amamager_name;
                $project["amamager_phone"] = $p_amamager_phone;
                $project["manager_id"] = $manager_id;
                $project["manager_name"] = $p_manager_name;
                $project["manager_phone"] = $p_manager_phone;
                $project["engineer_id"] = $engineer_id;
                $project["engineer_name"] = $p_engineer_name;
                $project["engineer_phone"] = $p_engineer_phone;
                $project["collection_id"] = 82;
                $project["operate_id"] = 84;
                $project["engineering_id"] = 83;
                $project["server_id"] = 199;
                $project["topmanager_id"] = 200;
                $r = (new HlappProject())->saveOrUpdata($project);
                Db::commit();
            } catch (\Exception $e) {
                $message = $p_name . "项目插入失败";
                \Log::ERROR($message);
                \Log::ERROR($e->getMessage());
                Db::rollback();
                $result = $message;
                break;
            }
        }
        return $result;
    }

    /**
     * 判断手机号是否存在，存在返回id，不存在插入返回插入id
     * @param $name
     * @param $phone
     * @param $time
     * @param $partId
     * @return false|int
     */
    private function insertNotExit($name, $phone, $time, $partId)
    {
        $m = new HlappMember();
        $member = $m->where('phone', $phone)->find();
        if ($member) {
            $id = $member['id'];
        } else {
            $user['name'] = $name;
            $user['phone'] = $phone;
            $user['create_time'] = $time;
            $user['partId'] = $partId;
            $id = $m->saveOrUpdata($user);
        }
        return $id;
    }
}